package com.ztom.top100;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 电话号码的字母组合
 * <p>
 * https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/
 *
 * @author ZhangTao
 */
public class Code09LetterCombinations {

    public List<String> letterCombinations(String digits) {
        List<String> res = new ArrayList<>();
        if (digits == null || digits.length() == 0) {
            return res;
        }
        Map<Character, String> phoneMap = new HashMap<Character, String>() {{
            put('2', "abc");
            put('3', "def");
            put('4', "ghi");
            put('5', "jkl");
            put('6', "mno");
            put('7', "pqrs");
            put('8', "tuv");
            put('9', "wxyz");
        }};

        backtrack(res, phoneMap, digits, 0, new StringBuilder());
        return res;
    }

    /**
     * 回溯: 去下一个位置找, 找到最后位置收集答案, 并恢复现场
     *
     * @param combinations
     * @param phoneMap
     * @param digits
     * @param index
     * @param combination
     */
    public void backtrack(List<String> combinations, Map<Character, String> phoneMap, String digits, int index, StringBuilder combination) {
        if (index == digits.length()) {
            combinations.add(combination.toString());
            return;
        }

        char digit = digits.charAt(index);
        String letters = phoneMap.get(digit);
        for (int i = 0; i < letters.length(); i++) {
            combination.append(letters.charAt(i));
            // 去下一个位置
            backtrack(combinations, phoneMap, digits, index + 1, combination);
            // 删除当前位置的字符, 回溯
            combination.deleteCharAt(index);
        }
    }
}
